#include "widget.h"

#include <osgQOpenGL/osgQOpenGLWidget>

#include <QBoxLayout>

#include <osgDB/ReadFile>

#include <osgViewer/Viewer>

#include <osgUtil/Optimizer>

#include <osgGA/TrackballManipulator>

#include <osgEarth/TerrainOptions>

#include <osgEarth/Config>

#include <osgEarth/MapNode>

#include <osgEarth/EarthManipulator>
#include <osgEarth/MapNode>

Widget::Widget(QWidget* parent) : QWidget(parent) {
	resize(1024, 768);

	QHBoxLayout* pLayout = new QHBoxLayout(this);

	pLayout->setMargin(0);

	osgQOpenGLWidget* pOsgW = new osgQOpenGLWidget(this);

	pLayout->addWidget(pOsgW);

	connect(pOsgW, SIGNAL(initialized()), this, SLOT(initOsg()));
}

Widget::~Widget() {}

void Widget::initOsg() {
	osgViewer::Viewer* pViewer = ((osgQOpenGLWidget*)sender())->getOsgViewer();
	pViewer->setCameraManipulator(new osgGA::TrackballManipulator());

	osgEarth::Config c;
	c.add("elevation_smoothing", false);
	osgEarth::TerrainOptions to(c);
	osgEarth::MapNode::Options defMNO;
	defMNO.terrain().setDefault(to);
	osg::ref_ptr<osgDB::Options> options = new osgDB::Options();
	options->setPluginStringData("osgEarth.defaultOptions", defMNO.getConfig().toJSON());
	osg::Node* pNode = osgDB::readNodeFile("simple.earth", options);

	//加载osgEarth需使用osgEarth::EarthManipulator控制器
	osg::ref_ptr<osgEarth::EarthManipulator> earthManipulator = new osgEarth::EarthManipulator();
	pViewer->setCameraManipulator(earthManipulator);

	osgUtil::Optimizer optimizer;
	optimizer.optimize(pNode);

	pViewer->setSceneData(pNode);
	//====================单独加载模型功能正常======================
	//osgViewer::Viewer* pViewer = ((osgQOpenGLWidget
	//	*)sender())->getOsgViewer();

	//pViewer->setCameraManipulator(new osgGA::TrackballManipulator());

	//osg::Node* pNode1 = osgDB::readNodeFile("../data/tree.osg");
	////osg::Node* pNode1 = osgDB::readNodeFile("simple.earth");

	//osgUtil::Optimizer optimizer;

	//optimizer.optimize(pNode1);

	//pViewer->setSceneData(pNode1);
}